package cn.tyf.service.imp;


import cn.tyf.common.ConstAutoConfig;
import cn.tyf.domain.User;
import cn.tyf.service.RecordService;
import cn.tyf.service.UserService;
import cn.tyf.util.HttpClientUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.lang.annotation.Target;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Service
public class DeviceService<obj> {
    private String uri = "";
    Boolean flag = false;
    @Autowired
    private ConstAutoConfig constAutoConfig;
    @Autowired
    private HttpClientUtil httpClient;
    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;

    private boolean status = false;

    private double min = 20.0;

    @PostConstruct
    public void initDevice() {

        Object obj = new Object();
        //查询设备状态
        new Thread(() -> {
            synchronized (obj) {
                if (flag) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    while (true) {
                        uri = constAutoConfig.getDEVICE_URL() + "/devices/status?devIds=" + constAutoConfig.getDeviceId() + "";
                        try {
                            JSONObject jsonObject = httpClient.doGet(uri, constAutoConfig.getApiKey());
                            JSONObject data = (JSONObject) jsonObject.get("data");
                            JSONArray array = (JSONArray) data.get("devices");
                            JSONObject msg = JSONObject.fromObject(array.get(0));
                            flag = (Boolean) msg.get("online");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (flag) {
                            try {
                                obj.wait(1200000);
                                obj.notify();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }
        }).start();

        //点灯
        new Thread(() -> {
            synchronized (obj) {
                if (flag == false) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    String raw_time = "";
                    String raw_card = "";
                    int i = 1;
                    while (true) {
                        //获取刷卡
                        uri = constAutoConfig.getDEVICE_URL() + "/devices/" + constAutoConfig.getDeviceId() + "/datastreams";
                        Integer door = 0;
                        String time = "";
                        String card = "";
                        try {
                            JSONObject jsonObject = httpClient.doGet(uri, constAutoConfig.getApiKey());
                            JSONArray data = (JSONArray) jsonObject.get("data");
                            JSONObject jsonObject1 = (JSONObject) data.get(0);
                            door = (Integer) jsonObject1.get("current_value");
                            JSONObject jsonObject2 = (JSONObject) data.get(1);
                            time = (String) jsonObject2.get("update_at");
                            card = (String) jsonObject2.get("current_value");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (i == 1) {
                            raw_time = time;
                            raw_card = card;
                            i = 0;
                            continue;
                        }
                        //前一次双卡的时间和最新时间是否相同
                        if (raw_time.equals(time) || card.equals("") || raw_card.equals(card) && raw_time.equals(time)) {
                            continue;
                        } else {
                            //查询此卡是否存在
                            User user = userService.findByRid(card);
                            //此卡存在
                            if (user != null && user.getFlag() == 1) {
                                raw_time = time;
                                raw_card = card;
                                //添加访问记录
                                recordService.addAnnal(card, time, door);

                                uri = constAutoConfig.getDEVICE_URL() + "/cmds?device_id=" + constAutoConfig.getDeviceId() + "";
                                Map<String, String> parameter = new HashMap<>();
                                parameter.put("led", "A11");
                                try {
                                    httpClient.doPost(uri, constAutoConfig.getApiKey(), parameter);
                                    //开门5秒后关门
                                    Thread.sleep(5000);
                                    uri = constAutoConfig.getDEVICE_URL() + "/cmds?device_id=" + constAutoConfig.getDeviceId() + "";
                                    Map<String, String> parameter2 = new HashMap<>();
                                    parameter2.put("led", "A10");
                                    httpClient.doPost(uri, constAutoConfig.getApiKey(), parameter2);
                                } catch (IOException | InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (flag == false) {
                            try {
                                obj.wait();
                                obj.notify();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

    }

    public double getMin() {
        return min;
    }

    public void setMin(double min) {
        this.min = min;
    }

    /**
     * 查询设备是否在线，每5分钟查询一次
     *
     * @return
     */
    @Scheduled(initialDelay = 10000,fixedDelay = 300000)
    public boolean getStatus() {
        try {
            JSONObject jsonObject = httpClient.doGet("http://api.heclouds.com/devices/609804034",
                    "r0cRmC5IEzfKJVbR5xCIengA0bE=");
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode online = objectMapper.readTree(String.valueOf(jsonObject)).get("data").get("online");
            status = online.booleanValue();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return status;
    }

    @Scheduled(cron = "* * 9,12,13,14,17,22 * * ?") //每天9,12,13,14,17,22 运行一次
    public boolean monitorWater() {
        double current_value = 30.0;  //默认湿度
        if (status) {   //设备是否在线
            try {

                JSONObject jsonObject = httpClient.doGet("http://api.heclouds.com/devices/609804034/datastreams/temp",
                        "r0cRmC5IEzfKJVbR5xCIengA0bE=");
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode jsonNode = objectMapper.readTree(String.valueOf(jsonObject)).get("data").get("current_value");
                current_value = jsonNode.doubleValue();
                if (current_value < min) { //当湿度小于预设值是
                    //开始浇水
                    uri = constAutoConfig.getDEVICE_URL() + "/cmds?device_id=" + constAutoConfig.getDeviceId() + "";
                    Map<String, String> parameter = new HashMap<>();
                    parameter.put("led", "A61");
                    //如果发送浇水指令不成功。则一直发送并查询设备状态
                    while (true) {
                        JSONObject jsonObject1 = httpClient.doPost(uri, constAutoConfig.getApiKey(), parameter);
                        int errno = objectMapper.readTree(String.valueOf(jsonObject1)).get("errno").intValue();
                        if (errno == 0) {
                            break;
                        }
                        getStatus();
                    }
                    //浇水5分钟
                    for (int i = 0; i < 5; i++) {
                        Thread.sleep(60000);
                    }
                    //关闭浇水
                    uri = constAutoConfig.getDEVICE_URL() + "/cmds?device_id=" + constAutoConfig.getDeviceId() + "";
                    Map<String, String> parameter2 = new HashMap<>();
                    parameter2.put("led", "A60");
                    JSONObject jsonObject1 = httpClient.doPost(uri, constAutoConfig.getApiKey(), parameter2);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
